package managers.conversationManager.services;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;

import managers.OptionsManager;
import managers.conversationManager.ConversationManager;
import managers.messengerManager.MessengerManager;
import managers.messengerManager.services.Service;
import spotGUI.floatingChatGUI.FloatingChat;
import spotGUI.floatingChatGUI.SendFilePanel;
import utils.StackTracePrinter;
import utils.UserData;
import audio.AudioManager;

public class SendFile extends Service {

	public static final int FT_ACCEPT = 0;
	public static final int FT_REFUSE = -1;

	private Socket socket;

	private ConversationManager convManager = ConversationManager.getSharedInstance();
	
	private DataInputStream dis;
	private DataOutputStream dos;

	private Properties soundOptions = OptionsManager.getSharedInstance().getOptionGroup("soundPopup");

	private FloatingChat relatedChat;
	private SendFilePanel ftPanel;
	private File f;

	public SendFile(UserData user,  File f) throws IOException {
		
		super("SendFile");
		relatedChat = convManager.getChatManager().getChat((Integer) user.getProperty("id"));
		this.f = f;
		System.out.println(user.getProperty("ipAddress")+" "+user.getProperty("fileTransferPort"));
		socket = new Socket((InetAddress) user.getProperty("ipAddress"), (Integer) user.getProperty("fileTransferPort"));
		
		dis = new DataInputStream(socket.getInputStream());
		dos = new DataOutputStream(socket.getOutputStream());

		dos.writeInt(MessengerManager.getSharedInstance().getUserId());
		
	}

	@Override
	public void run() {

		try {

			ftPanel = relatedChat.getFiletransferManager().getSendFileFeedback();
			ftPanel.lock(true);
			ftPanel.updateLogBar("Attendi che "+relatedChat.getReceiverName()+" risponda.", null);
			ftPanel.setVisible(true);
			relatedChat.enableFeatures("fileTransfer", false);

			int choice;

			choice = dis.readInt();
			if (choice == FT_ACCEPT) {
				ftPanel.setSending(true);
				ftPanel.updateLogBar("Invio in corso...", null);
				dos.writeInt(f.getName().length());
				dos.writeChars(f.getName());
				dos.writeInt(new Long(f.length()).intValue());
				FileInputStream fis = new FileInputStream(f);
				byte[] bytes = new byte[new Long(f.length()).intValue()]; 
				fis.read(bytes);
				socket.getOutputStream().write(bytes);
				ftPanel.setSending(false);
				ftPanel.updateLogBar("Invio completato.", null);
				playSound("fileTransferComplete");
				relatedChat.setVisible(true);
			} else {
				ftPanel.updateLogBar(relatedChat.getReceiverName()+" ha rifiutato la ricezione.", null);
				playSound("fileTransferError");
				relatedChat.setVisible(true);
			}
			closeTransfer();

		} catch (IOException e) {
			StackTracePrinter.print(e);
			closeTransfer();
			playSound("fileTransferError");
			ftPanel.updateLogBar("Impossibile inviare il file", null);
			relatedChat.setVisible(true);
		}
	}

	private void closeTransfer() {
		ftPanel.lock(false);
		relatedChat.enableFeatures("fileTransfer", true);
		try {
			socket.close();
			dis.close();
			dos.close();
		} catch (IOException e) {
			//do nothing
			StackTracePrinter.print(e);
		}
	}

	private void playSound(String event) {
		if (soundOptions.getProperty(event+".SOUND").equals("true"))
			try {
				String[] attributes = soundOptions.getProperty(event+".SOUNDPATH").split(",");
				AudioManager.getSharedInstance().play(attributes[0], attributes);
			} catch (Exception e) {
				//do nothing
				StackTracePrinter.print(e);
			}
	}

}
